package com.woniu.shirocore;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * @author Rain
 * @Description :
 * @date 2022/09/05 15:45
 */
public class MyRealmDemo extends AuthorizingRealm {
    private final String REALM_NAME = "MyRealmDemo";
    /**
     * 认证方法
     * @param token
     * @return null
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        if (token instanceof UsernamePasswordToken){
            UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
            String username = usernamePasswordToken.getUsername();
            String password = "123456";

            if (new String(usernamePasswordToken.getPassword()).equals(password)){
                System.out.println("登录成功");
                return new SimpleAuthenticationInfo(username, password,REALM_NAME);
            }else {
                return null;
            }
        }
        return null;
    }

    /**
     * 授权方法
     * @param principalCollection
     * @return null
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        if (principalCollection.getRealmNames().contains(REALM_NAME)){
            //模拟数据库中查出的角色和权限封装到set中
            Set<String> roles = new HashSet<>();
            roles.add("admin");
            roles.add("manager");
            roles.add("tourist");
            Set<String> perms = new HashSet<>();//封装权限
            perms.add("manager:add");
            perms.add("manager:edit");
            perms.add("manager:del");
            perms.add("manager:find");
            //添加角色信息和权限信息到SimpleAuthorizationInfo并return
            SimpleAuthorizationInfo sai = new SimpleAuthorizationInfo();
            sai.addRoles(roles);
            sai.addStringPermissions(perms);
            return sai;
        }
        return null;
    }
}
